package com.hhxy.config;

import com.hhxy.filter.JwtAuthenticationTokenFilter;
import com.hhxy.handler.security.AccessDeniedImplHandler;
import com.hhxy.handler.security.AuthenticationEntryPointImplHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author ghp
 * @date 2023/4/25
 * @title
 * @description
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Resource
    private AccessDeniedImplHandler accessDeniedHandler;

    @Resource
    private AuthenticationEntryPointImplHandler authenticationEntryPoint;

    /**
     * 注入AuthenticationManager对象，用于登录认证
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 使用BCryptPasswordEncoder进行加密（SpringSecurity默认是使用PasswordEncoder进行加密）
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 初始化配置
        http.csrf().disable() // 关闭csrf，REST API是无状态的，无需防止CSRF攻击
                // 禁用Session，启用无状态模式（默认会讲权限信息存入Session中，如果SecurityContext取不到数据会查找Session）
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .antMatchers("/login").anonymous() // 对于登录接口, 允许匿名访问
                // 需要登录才能访问的接口
                .antMatchers("/logout").authenticated() // 退出
                .antMatchers("/comment").authenticated() // 新增评论
                .antMatchers("/user/userInfo").authenticated() // 查看用户信息
                .antMatchers("/upload").authenticated() // 上传文件
                // 除上面外的所有请求全部不需要鉴权认证
                .anyRequest().permitAll();

        // 配置异常处理器
        http.exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);

        // 关闭默认的注销功能
        http.logout().disable();

        // 把jwtAuthenticationTokenFilter添加到UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 允许跨域
        http.cors();
    }


}
